<template>
  <div class="settings-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>系统设置</h1>
        <p>管理系统配置和参数</p>
      </div>
    </div>

    <!-- 设置菜单 -->
    <div class="settings-layout">
      <div class="settings-menu">
        <el-menu
          v-model="activeMenu"
          mode="vertical"
          @select="handleMenuSelect"
        >
          <el-menu-item index="general">
            <el-icon><Setting /></el-icon>
            <span>基本设置</span>
          </el-menu-item>
          <el-menu-item index="security">
            <el-icon><Lock /></el-icon>
            <span>安全设置</span>
          </el-menu-item>
          <el-menu-item index="notification">
            <el-icon><Bell /></el-icon>
            <span>通知设置</span>
          </el-menu-item>
          <el-menu-item index="system">
            <el-icon><Monitor /></el-icon>
            <span>系统配置</span>
          </el-menu-item>
          <el-menu-item index="backup">
            <el-icon><FolderOpened /></el-icon>
            <span>备份恢复</span>
          </el-menu-item>
        </el-menu>
      </div>

      <div class="settings-content">
        <!-- 基本设置 -->
        <div v-if="activeMenu === 'general'" class="setting-panel">
          <div class="panel-header">
            <h3>基本设置</h3>
            <p>配置系统的基本信息和参数</p>
          </div>
          
          <el-form
            ref="generalFormRef"
            :model="generalSettings"
            :rules="generalRules"
            label-width="120px"
          >
            <el-form-item label="系统名称" prop="system_name">
              <el-input v-model="generalSettings.system_name" />
            </el-form-item>
            <el-form-item label="系统描述">
              <el-input
                v-model="generalSettings.system_description"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <el-form-item label="系统版本" prop="system_version">
              <el-input v-model="generalSettings.system_version" readonly />
            </el-form-item>
            <el-form-item label="时区设置" prop="timezone">
              <el-select v-model="generalSettings.timezone" style="width: 100%">
                <el-option label="北京时间 (UTC+8)" value="Asia/Shanghai" />
                <el-option label="东京时间 (UTC+9)" value="Asia/Tokyo" />
                <el-option label="纽约时间 (UTC-5)" value="America/New_York" />
                <el-option label="伦敦时间 (UTC+0)" value="Europe/London" />
              </el-select>
            </el-form-item>
            <el-form-item label="语言设置" prop="language">
              <el-select v-model="generalSettings.language" style="width: 100%">
                <el-option label="简体中文" value="zh-CN" />
                <el-option label="English" value="en-US" />
                <el-option label="日本語" value="ja-JP" />
              </el-select>
            </el-form-item>
            <el-form-item label="主题设置" prop="theme">
              <el-alert
                title="提示"
                type="info"
                :closable="false"
                show-icon
                style="margin-bottom: 12px;"
              >
                <template #default>
                  <span>主题设置已移至个人中心的"偏好设置"标签页，每个用户可以独立设置自己的主题偏好。</span>
                </template>
              </el-alert>
              <el-radio-group v-model="generalSettings.theme" disabled>
                <el-radio label="light">浅色主题</el-radio>
                <el-radio label="dark">深色主题</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveGeneral" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="handleResetGeneral">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 安全设置 -->
        <div v-if="activeMenu === 'security'" class="setting-panel">
          <div class="panel-header">
            <h3>安全设置</h3>
            <p>配置系统安全策略和参数</p>
          </div>
          
          <el-form
            ref="securityFormRef"
            :model="securitySettings"
            :rules="securityRules"
            label-width="150px"
          >
            <el-form-item label="密码策略">
              <div class="security-group">
                <el-checkbox v-model="securitySettings.password_min_length_enabled">
                  启用最小长度限制
                </el-checkbox>
                <el-input-number
                  v-model="securitySettings.password_min_length"
                  :min="6"
                  :max="20"
                  :disabled="!securitySettings.password_min_length_enabled"
                  style="margin-left: 12px; width: 120px"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <div class="security-group">
                <el-checkbox v-model="securitySettings.password_require_uppercase">
                  要求包含大写字母
                </el-checkbox>
              </div>
            </el-form-item>
            <el-form-item>
              <div class="security-group">
                <el-checkbox v-model="securitySettings.password_require_lowercase">
                  要求包含小写字母
                </el-checkbox>
              </div>
            </el-form-item>
            <el-form-item>
              <div class="security-group">
                <el-checkbox v-model="securitySettings.password_require_numbers">
                  要求包含数字
                </el-checkbox>
              </div>
            </el-form-item>
            <el-form-item>
              <div class="security-group">
                <el-checkbox v-model="securitySettings.password_require_symbols">
                  要求包含特殊字符
                </el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label="会话管理">
              <div class="security-group">
                <el-checkbox v-model="securitySettings.session_timeout_enabled">
                  启用会话超时
                </el-checkbox>
                <el-input-number
                  v-model="securitySettings.session_timeout_minutes"
                  :min="5"
                  :max="1440"
                  :disabled="!securitySettings.session_timeout_enabled"
                  style="margin-left: 12px; width: 120px"
                />
                <span style="margin-left: 8px">分钟</span>
              </div>
            </el-form-item>
            <el-form-item label="登录限制">
              <div class="security-group">
                <el-checkbox v-model="securitySettings.login_attempts_enabled">
                  启用登录失败限制
                </el-checkbox>
                <el-input-number
                  v-model="securitySettings.max_login_attempts"
                  :min="3"
                  :max="10"
                  :disabled="!securitySettings.login_attempts_enabled"
                  style="margin-left: 12px; width: 120px"
                />
                <span style="margin-left: 8px">次</span>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSecurity" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="handleResetSecurity">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 通知设置 -->
        <div v-if="activeMenu === 'notification'" class="setting-panel">
          <div class="panel-header">
            <h3>通知设置</h3>
            <p>配置系统通知和消息推送</p>
          </div>
          
          <el-form
            ref="notificationFormRef"
            :model="notificationSettings"
            label-width="150px"
          >
            <el-form-item label="邮件通知">
              <div class="notification-group">
                <el-switch v-model="notificationSettings.email_enabled" />
                <span style="margin-left: 12px">启用邮件通知</span>
              </div>
            </el-form-item>
            <el-form-item label="SMTP配置" v-if="notificationSettings.email_enabled">
              <div class="smtp-config">
                <el-form-item label="SMTP服务器">
                  <el-input v-model="notificationSettings.smtp_host" />
                </el-form-item>
                <el-form-item label="端口">
                  <el-input-number v-model="notificationSettings.smtp_port" :min="1" :max="65535" />
                </el-form-item>
                <el-form-item label="用户名">
                  <el-input v-model="notificationSettings.smtp_username" />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input v-model="notificationSettings.smtp_password" type="password" show-password />
                </el-form-item>
                <el-form-item label="加密方式">
                  <el-select v-model="notificationSettings.smtp_encryption">
                    <el-option label="无" value="none" />
                    <el-option label="SSL" value="ssl" />
                    <el-option label="TLS" value="tls" />
                  </el-select>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="通知类型">
              <div class="notification-types">
                <el-checkbox v-model="notificationSettings.notify_task_assigned">
                  任务分配通知
                </el-checkbox>
                <el-checkbox v-model="notificationSettings.notify_task_completed">
                  任务完成通知
                </el-checkbox>
                <el-checkbox v-model="notificationSettings.notify_project_update">
                  项目更新通知
                </el-checkbox>
                <el-checkbox v-model="notificationSettings.notify_deadline_reminder">
                  截止日期提醒
                </el-checkbox>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveNotification" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="handleTestEmail" :loading="testing">
                测试邮件
              </el-button>
              <el-button @click="handleResetNotification">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 系统配置 -->
        <div v-if="activeMenu === 'system'" class="setting-panel">
          <div class="panel-header">
            <h3>系统配置</h3>
            <p>配置系统运行参数和性能设置</p>
          </div>
          
          <el-form
            ref="systemFormRef"
            :model="systemSettings"
            label-width="150px"
          >
            <el-form-item label="文件上传">
              <div class="system-group">
                <el-form-item label="最大文件大小">
                  <el-input-number
                    v-model="systemSettings.max_file_size_mb"
                    :min="1"
                    :max="1024"
                  />
                  <span style="margin-left: 8px">MB</span>
                </el-form-item>
                <el-form-item label="允许的文件类型">
                  <el-input
                    v-model="systemSettings.allowed_file_types"
                    placeholder="如: jpg,png,pdf,doc,docx"
                  />
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="数据库">
              <div class="system-group">
                <el-form-item label="连接池大小">
                  <el-input-number
                    v-model="systemSettings.db_pool_size"
                    :min="5"
                    :max="100"
                  />
                </el-form-item>
                <el-form-item label="查询超时">
                  <el-input-number
                    v-model="systemSettings.db_query_timeout"
                    :min="5"
                    :max="300"
                  />
                  <span style="margin-left: 8px">秒</span>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="缓存设置">
              <div class="system-group">
                <el-switch v-model="systemSettings.cache_enabled" />
                <span style="margin-left: 12px">启用缓存</span>
                <el-form-item label="缓存过期时间" v-if="systemSettings.cache_enabled">
                  <el-input-number
                    v-model="systemSettings.cache_ttl_minutes"
                    :min="1"
                    :max="1440"
                  />
                  <span style="margin-left: 8px">分钟</span>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="日志设置">
              <div class="system-group">
                <el-form-item label="日志级别">
                  <el-select v-model="systemSettings.log_level">
                    <el-option label="DEBUG" value="debug" />
                    <el-option label="INFO" value="info" />
                    <el-option label="WARNING" value="warning" />
                    <el-option label="ERROR" value="error" />
                  </el-select>
                </el-form-item>
                <el-form-item label="日志保留天数">
                  <el-input-number
                    v-model="systemSettings.log_retention_days"
                    :min="1"
                    :max="365"
                  />
                  <span style="margin-left: 8px">天</span>
                </el-form-item>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSystem" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="handleResetSystem">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 备份恢复 -->
        <div v-if="activeMenu === 'backup'" class="setting-panel">
          <div class="panel-header">
            <h3>备份恢复</h3>
            <p>管理系统数据备份和恢复</p>
          </div>
          
          <div class="backup-section">
            <el-card class="backup-card">
              <template #header>
                <div class="card-header">
                  <span>数据备份</span>
                  <el-button type="primary" @click="handleCreateBackup" :loading="backing">
                    创建备份
                  </el-button>
                </div>
              </template>
              
              <div class="backup-settings">
                <el-form label-width="120px">
                  <el-form-item label="自动备份">
                    <el-switch v-model="backupSettings.auto_backup_enabled" />
                  </el-form-item>
                  <el-form-item label="备份频率" v-if="backupSettings.auto_backup_enabled">
                    <el-select v-model="backupSettings.backup_frequency">
                      <el-option label="每日" value="daily" />
                      <el-option label="每周" value="weekly" />
                      <el-option label="每月" value="monthly" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="备份时间">
                    <el-time-picker
                      v-model="backupSettings.backup_time"
                      format="HH:mm"
                      value-format="HH:mm"
                      placeholder="选择备份时间"
                    />
                  </el-form-item>
                  <el-form-item label="保留份数">
                    <el-input-number
                      v-model="backupSettings.max_backup_count"
                      :min="1"
                      :max="30"
                    />
                  </el-form-item>
                  <el-form-item label="压缩备份">
                    <el-switch v-model="backupSettings.backup_compression" />
                  </el-form-item>
                  <el-form-item label="加密备份">
                    <el-switch v-model="backupSettings.backup_encryption" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSaveBackup" :loading="saving">
                      保存设置
                    </el-button>
                    <el-button @click="handleResetBackup">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>

            <el-card class="backup-card">
              <template #header>
                <span>备份历史</span>
              </template>
              
              <el-table :data="backupHistory" v-loading="loadingBackups">
                <el-table-column prop="filename" label="备份文件" />
                <el-table-column prop="size" label="文件大小">
                  <template #default="{ row }">
                    {{ formatFileSize(row.size) }}
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间">
                  <template #default="{ row }">
                    {{ formatDateTime(row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                      {{ row.status === 'success' ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="{ row }">
                    <el-button
                      size="small"
                      :loading="downloadingId === row.id"
                      @click="handleDownloadBackup(row)"
                    >
                      下载
                    </el-button>
                    <el-button size="small" type="warning" @click="handleRestoreBackup(row)">
                      恢复
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDeleteBackup(row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRaw } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Setting,
  Lock,
  Bell,
  Monitor,
  FolderOpened
} from '@element-plus/icons-vue'
import {
  getSystemSettings,
  updateGeneralSettings,
  updateSecuritySettings,
  updateNotificationSettings,
  updateSystemSettings,
  updateBackupSettings,
  testEmail,
  getBackupHistory,
  createBackup,
  deleteBackup,
  downloadBackup
} from '@/api/settings'
import type {
  GeneralSettings,
  SecuritySettings,
  NotificationSettings,
  SystemSettings,
  BackupSettings,
  BackupRecord,
  BackupRecordList,
  SystemSettingsResponse
} from '@/types/settings'
import { useThemeStore } from '@/stores/theme'

const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value))
const toPlainObject = <T>(state: T): T => clone(toRaw(state))
const unwrapResponseData = <T>(response: any): T => {
  const payload = response?.data ?? response
  if (payload && typeof payload === 'object' && 'success' in payload) {
    if (payload.success && 'data' in payload && payload.data !== undefined) {
      return payload.data as T
    }
    return (payload.data ?? payload) as T
  }
  return payload as T
}

// 主题store
const themeStore = useThemeStore()

// 响应式数据
const saving = ref(false)
const testing = ref(false)
const backing = ref(false)
const loadingBackups = ref(false)
const downloadingId = ref<string | null>(null)

// 当前激活的菜单
const activeMenu = ref('general')

// 表单引用
const generalFormRef = ref<FormInstance>()
const securityFormRef = ref<FormInstance>()
const notificationFormRef = ref<FormInstance>()
const systemFormRef = ref<FormInstance>()

const defaultGeneralSettings: GeneralSettings = {
  system_name: '项目管理系统',
  system_description: '现代化的项目管理和协作平台',
  system_version: '1.0.0',
  timezone: 'Asia/Shanghai',
  language: 'zh-CN',
  theme: 'light'
}

const defaultSecuritySettings: SecuritySettings = {
  password_min_length_enabled: true,
  password_min_length: 8,
  password_require_uppercase: true,
  password_require_lowercase: true,
  password_require_numbers: true,
  password_require_symbols: false,
  session_timeout_enabled: true,
  session_timeout_minutes: 120,
  login_attempts_enabled: true,
  max_login_attempts: 5
}

const defaultNotificationSettings: NotificationSettings = {
  email_enabled: false,
  smtp_host: '',
  smtp_port: 587,
  smtp_username: '',
  smtp_password: '',
  smtp_encryption: 'tls',
  notify_task_assigned: true,
  notify_task_completed: true,
  notify_project_update: true,
  notify_deadline_reminder: true
}

const defaultSystemSettings: SystemSettings = {
  max_file_size_mb: 50,
  allowed_file_types: 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,md',
  db_pool_size: 20,
  db_query_timeout: 30,
  cache_enabled: true,
  cache_ttl_minutes: 60,
  log_level: 'info',
  log_retention_days: 30
}

const defaultBackupSettings: BackupSettings = {
  auto_backup_enabled: false,
  backup_frequency: 'weekly',
  backup_time: '02:00',
  max_backup_count: 10,
  backup_compression: true,
  backup_encryption: false
}

// 基本设置
const generalSettings = reactive<GeneralSettings>({ ...defaultGeneralSettings })

// 安全设置
const securitySettings = reactive<SecuritySettings>({ ...defaultSecuritySettings })

// 通知设置
const notificationSettings = reactive<NotificationSettings>({ ...defaultNotificationSettings })

// 系统设置
const systemSettings = reactive<SystemSettings>({ ...defaultSystemSettings })

// 备份设置
const backupSettings = reactive<BackupSettings>({ ...defaultBackupSettings })

// 初始快照
const initialGeneralSettings = ref<GeneralSettings>(clone(defaultGeneralSettings))
const initialSecuritySettings = ref<SecuritySettings>(clone(defaultSecuritySettings))
const initialNotificationSettings = ref<NotificationSettings>(clone(defaultNotificationSettings))
const initialSystemSettings = ref<SystemSettings>(clone(defaultSystemSettings))
const initialBackupSettings = ref<BackupSettings>(clone(defaultBackupSettings))

// 备份历史
const backupHistory = ref<BackupRecord[]>([])

// 表单验证规则
const generalRules: FormRules = {
  system_name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  system_version: [
    { required: true, message: '请输入系统版本', trigger: 'blur' }
  ],
  timezone: [
    { required: true, message: '请选择时区', trigger: 'change' }
  ],
  language: [
    { required: true, message: '请选择语言', trigger: 'change' }
  ],
  theme: [
    { required: true, message: '请选择主题', trigger: 'change' }
  ]
}

const securityRules: FormRules = {}

// 菜单选择处理
const handleMenuSelect = (index: string) => {
  activeMenu.value = index
}

// 保存基本设置
const handleSaveGeneral = async () => {
  if (!generalFormRef.value) return
  
  try {
    await generalFormRef.value.validate()
    saving.value = true
    
    const payload = toPlainObject(generalSettings)
    await updateGeneralSettings(payload)
    initialGeneralSettings.value = clone(payload)
    
    // 注意：主题设置已移至个人中心，这里不再处理
    
    ElMessage.success('基本设置保存成功')
  } catch (error) {
    console.error('保存基本设置失败:', error)
    ElMessage.error('保存基本设置失败')
  } finally {
    saving.value = false
  }
}

// 重置基本设置
const handleResetGeneral = () => {
  Object.assign(generalSettings, initialGeneralSettings.value ?? defaultGeneralSettings)
}

// 保存安全设置
const handleSaveSecurity = async () => {
  try {
    saving.value = true
    
    const payload = toPlainObject(securitySettings)
    await updateSecuritySettings(payload)
    initialSecuritySettings.value = clone(payload)
    
    ElMessage.success('安全设置保存成功')
  } catch (error) {
    console.error('保存安全设置失败:', error)
    ElMessage.error('保存安全设置失败')
  } finally {
    saving.value = false
  }
}

// 重置安全设置
const handleResetSecurity = () => {
  Object.assign(securitySettings, initialSecuritySettings.value ?? defaultSecuritySettings)
}

// 保存通知设置
const handleSaveNotification = async () => {
  try {
    saving.value = true
    
    const payload = toPlainObject(notificationSettings)
    await updateNotificationSettings(payload)
    initialNotificationSettings.value = clone(payload)
    
    ElMessage.success('通知设置保存成功')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存通知设置失败')
  } finally {
    saving.value = false
  }
}

// 测试邮件
const handleTestEmail = async () => {
  try {
    if (!notificationSettings.email_enabled) {
      ElMessage.warning('请先启用邮件通知')
      return
    }
    testing.value = true
    
    await testEmail({
      to_email: 'test@example.com',
      subject: '系统邮件测试',
      content: '这是一封测试邮件，用于验证邮件配置是否正确。'
    })
    
    ElMessage.success('测试邮件发送成功')
  } catch (error) {
    console.error('测试邮件发送失败:', error)
    ElMessage.error('测试邮件发送失败')
  } finally {
    testing.value = false
  }
}

// 重置通知设置
const handleResetNotification = () => {
  Object.assign(notificationSettings, initialNotificationSettings.value ?? defaultNotificationSettings)
}

// 保存系统设置
const handleSaveSystem = async () => {
  try {
    saving.value = true
    
    const payload = toPlainObject(systemSettings)
    await updateSystemSettings(payload)
    initialSystemSettings.value = clone(payload)
    
    ElMessage.success('系统设置保存成功')
  } catch (error) {
    console.error('保存系统设置失败:', error)
    ElMessage.error('保存系统设置失败')
  } finally {
    saving.value = false
  }
}

// 重置系统设置
const handleResetSystem = () => {
  Object.assign(systemSettings, initialSystemSettings.value ?? defaultSystemSettings)
}

// 保存备份设置
const handleSaveBackup = async () => {
  try {
    saving.value = true
    
    const payload = toPlainObject(backupSettings)
    await updateBackupSettings(payload)
    initialBackupSettings.value = clone(payload)
    
    ElMessage.success('备份设置保存成功')
  } catch (error) {
    console.error('保存备份设置失败:', error)
    ElMessage.error('保存备份设置失败')
  } finally {
    saving.value = false
  }
}

// 重置备份设置
const handleResetBackup = () => {
  Object.assign(backupSettings, initialBackupSettings.value ?? defaultBackupSettings)
}

// 创建备份
const handleCreateBackup = async () => {
  try {
    backing.value = true
    
    await createBackup()
    
    ElMessage.success('备份创建成功')
    // 刷新备份历史
    await fetchBackupHistory()
  } catch (error) {
    console.error('创建备份失败:', error)
    ElMessage.error('创建备份失败')
  } finally {
    backing.value = false
  }
}

// 下载备份
const getFilenameFromDisposition = (disposition?: string) => {
  if (!disposition) return ''
  const filenameMatch = disposition.match(/filename\*?=(?:UTF-8'')?["']?([^"';]+)["']?/)
  if (filenameMatch && filenameMatch[1]) {
    try {
      return decodeURIComponent(filenameMatch[1])
    } catch (error) {
      console.warn('解析备份文件名失败，使用原始值', error)
      return filenameMatch[1]
    }
  }
  return ''
}

const handleDownloadBackup = async (backup: BackupRecord) => {
  if (!backup?.id) {
    ElMessage.error('缺少备份标识，无法下载')
    return
  }
  try {
    downloadingId.value = backup.id
    const response = await downloadBackup(backup.id)
    const blob = response.data as Blob
    const disposition = response.headers?.['content-disposition'] as string | undefined
    let filename = getFilenameFromDisposition(disposition) || backup.filename || `backup_${Date.now()}.json`

    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`备份文件 ${filename} 正在下载`)
  } catch (error) {
    console.error('下载备份失败:', error)
    ElMessage.error('下载备份失败')
  } finally {
    downloadingId.value = null
  }
}

// 恢复备份
const handleRestoreBackup = async (backup: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复备份 "${backup.filename}" 吗？此操作将覆盖当前数据，请谨慎操作。`,
      '恢复备份',
      { type: 'warning' }
    )
    
    ElMessage.success('备份恢复成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复备份失败:', error)
      ElMessage.error('恢复备份失败')
    }
  }
}

// 删除备份
const handleDeleteBackup = async (backup: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除备份 "${backup.filename}" 吗？此操作不可恢复。`,
      '删除备份',
      { type: 'warning' }
    )
    
    await deleteBackup(backup.id)
    
    ElMessage.success('备份删除成功')
    await fetchBackupHistory()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除备份失败:', error)
      ElMessage.error('删除备份失败')
    }
  }
}

// 获取备份历史
const fetchBackupHistory = async () => {
  try {
    loadingBackups.value = true
    const response = await getBackupHistory()
    
    const historyData = unwrapResponseData<BackupRecordList | BackupRecord[]>(response)
    if (Array.isArray(historyData)) {
      backupHistory.value = historyData
    } else {
      const items = historyData.items ?? (historyData as any).backups ?? []
      backupHistory.value = items
    }
  } catch (error) {
    console.error('获取备份历史失败:', error)
  } finally {
    loadingBackups.value = false
  }
}

// 辅助函数
const formatFileSize = (size: number) => {
  if (!size) return '-'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size
  
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  
  return `${fileSize.toFixed(1)} ${units[index]}`
}

const formatDateTime = (datetime: string | Date | null | undefined) => {
  if (!datetime) return '-'
  const date = datetime instanceof Date ? datetime : new Date(datetime)
  if (Number.isNaN(date.getTime())) return '-'
  return date.toLocaleString('zh-CN')
}

// 初始化
onMounted(async () => {
  try {
    // 获取系统设置
    const response = await getSystemSettings()
    
    const settings = unwrapResponseData<SystemSettingsResponse>(response)
    
    // 更新各个设置模块的数据
    Object.assign(generalSettings, settings.general || {})
    Object.assign(securitySettings, settings.security || {})
    Object.assign(notificationSettings, settings.notification || {})
    Object.assign(systemSettings, settings.system || {})
    Object.assign(backupSettings, settings.backup || {})

    // 注意：主题设置已移至个人中心，这里不再同步

    // 刷新各模块的初始快照
    initialGeneralSettings.value = toPlainObject(generalSettings)
    initialSecuritySettings.value = toPlainObject(securitySettings)
    initialNotificationSettings.value = toPlainObject(notificationSettings)
    initialSystemSettings.value = toPlainObject(systemSettings)
    initialBackupSettings.value = toPlainObject(backupSettings)
    
    // 获取备份历史
    await fetchBackupHistory()
  } catch (error) {
    console.error('初始化系统设置失败:', error)
    ElMessage.error('加载系统设置失败')
  }
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
  background: var(--bg-secondary);
  min-height: 100vh;
  transition: background-color 0.3s ease, color 0.3s ease;
  color: var(--text-primary);
}

.page-header {
  margin-bottom: 24px;
}

.header-left h1 {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
  transition: color 0.3s ease;
}

.header-left p {
  color: var(--text-secondary);
  margin: 0;
  transition: color 0.3s ease;
}

.settings-layout {
  display: flex;
  gap: 24px;
}

.settings-menu {
  width: 200px;
  flex-shrink: 0;
}

.settings-menu .el-menu {
  border-right: 1px solid var(--border-color);
  transition: border-color 0.3s ease;
}

.settings-content {
  flex: 1;
  min-width: 0;
}

.setting-panel {
  background: var(--bg-card);
  border-radius: 8px;
  padding: 24px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color-light);
  transition: all 0.3s ease;
}

.panel-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color-light);
  transition: border-color 0.3s ease;
}

.panel-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
  transition: color 0.3s ease;
}

.panel-header p {
  color: var(--text-secondary);
  margin: 0;
  transition: color 0.3s ease;
}

.security-group {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.notification-group {
  display: flex;
  align-items: center;
}

.smtp-config {
  width: 100%;
  padding: 16px;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.smtp-config .el-form-item {
  margin-bottom: 16px;
}

.notification-types {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.system-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.backup-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.backup-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.backup-settings {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-container {
    padding: 16px;
  }
  
  .settings-layout {
    flex-direction: column;
  }
  
  .settings-menu {
    width: 100%;
  }
  
  .settings-menu .el-menu {
    border-right: none;
    border-bottom: 1px solid #e5e7eb;
  }
  
  .setting-panel {
    padding: 16px;
  }
  
  .security-group,
  .notification-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .system-group {
    gap: 12px;
  }
}
</style>